package com.apes.fn.scm.advancePayment;

import com.apes.fn.crm.customerExpand.FnCustomerExpand;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.util.*;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.service.PartyRoleService;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 订金单
 *
 * @author wuq
 * @create 2020-03-17 18:01
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = AdvancePayment.CONST_TABLE_NAME)
public class AdvancePayment extends Model {
    public static final String CONST_TABLE_NAME = "Advance_Payment";

    @Id
    @Column(name = "id")
    @Comment("订金单号")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "订金单", prefix = "DJ%(company)%(yy)%(month)", padding = 5, useDateRange=true)
    private String id;

    @Comment("公司")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    private PartyRole company;

    @Comment("会员扩展信息")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "customer_expand_id", referencedColumnName = "id")
    private FnCustomerExpand customerExpand;

    @Transient
    private Map customerCar;


    public Map getCustomerCar() {
        if (customerExpand == null || customerExpand.getCarLicense() == null) return null;
        return MapUtil.mapper(
                "carLicense", customerExpand.getCarLicense(),
                "vendorCode", customerExpand.getVendorCode(),
                "customer", this.getCustomer()
        );
    }


    @Transient
    private Map customer;

    public Map getCustomer() {
        if (customerExpand == null || customerExpand.getMobile() == null) return null;
        return MapUtil.mapper(
                "realname", customerExpand.getRealname(),
                "vendorCode", customerExpand.getVendorCode(),
                "mobile", customerExpand.getMobile()
        );
    }

    @Comment("门店")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id", nullable = false)
    private Dept dept;

    @Column(name = "amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("金额")
    private double amount = 0;

    @Column(name = "state", length = 10, nullable = false)
    private String state = "sent";

    @Comment("源单据")
    @Column(name = "origin", length = 30)
    private String origin;

    //refundToAdvance:冲红转订金;forwardPay:提前收款生成订金;refund:退订金;
    @Comment("来源类型")
    @Column(name = "source_Type", length = 30)
    private String sourceType;

    @Transient
    private String originBusinessName;

    @Column(name = "source", length = 30)
    @Comment("来源单据")
    private String source;

    @Column(name = "source_business_type", length = 32)
    @Comment("来源单据类型")
    private String sourceBusinessType;

    @ManyToOne(fetch = FetchType.LAZY)
    @Comment("订金类型（onlinePay:线上支付, storePay:门店预收, advancePay:订金）")
    @JoinColumn(name = "advance_Pay_Type", referencedColumnName = "id")
    private Enumeration advancePayType;   // 订金类型（onlinePay:线上支付, storePay:门店预收, advancePay:订金）

    @Comment("订单备注")
    @Column(name = "remark", length = 120)
    private String remark;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_uid", referencedColumnName = "id")
    @Comment("审核人")
    private PartyRole approveUID; //审核

    @Comment("审批日期")
    @Column(name = "date_approve")
    private Date dateApprove;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "sales_Man", referencedColumnName = "id")
    @Comment("业务员")
    private PartyRole salesMan;

    @Comment("车险优惠方案金额")    // e 保养对账金额
    @Column(name = "insurance_Discounts_Amt", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double insuranceDiscountsAmt = 0;

    @Column(name = "calculate_flag", columnDefinition = ApesConst.FIELD_BOOLEAN_FALSE)
    @Comment("计费完成标记")
    private boolean calculateFlag = false;

    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<AdvancePaymentItem> paymentItems = new HashSet(); //订单行


    public Set<AdvancePaymentItem> getPaymentItems() {
        for (AdvancePaymentItem item : paymentItems) {
            // 去除数量为 0 的行
            if (item.getProductUomQty() == 0) {
                paymentItems.remove(item);
                continue;
            }
            item.setOrder(this);
        }
        return paymentItems;
    }

    @OneToMany(mappedBy = "payment", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<AdvancePaymentMethod> paymentMethodSet = new HashSet(); // 付款方式明细

    public Set<AdvancePaymentMethod> getPaymentMethodSet() {
        if ( paymentMethodSet == null || paymentMethodSet.isEmpty())  return new HashSet<>();
        for (AdvancePaymentMethod item : paymentMethodSet) {
            item.setPayment(this);
        }
        return paymentMethodSet;
    }

    @Transient
    private boolean payItemNotEqualAmount;

    public boolean bPayItemNotEqualAmount() {
        double itemamount = 0;
        for (AdvancePaymentItem item : paymentItems) {
            // 去除数量为 0 的行
            if (item.getProductUomQty() == 0) {
                continue;
            }
            itemamount = itemamount + item.getPriceTotal();
        }
        if(Arith.compare(itemamount, amount, 0.01) != 0){
            throw new RuntimeException("订金明细金额与订单总金额不相等！");
        }
        return false;
    }

    @Transient
    private boolean paymentNotEqualAmount;

    public boolean bPaymentNotEqualAmount() {
        double paymentacount =0;
        for (AdvancePaymentMethod item : paymentMethodSet) {
            if(item.getPaymentMethodType().getId().equals("09") && item.getCustomer()==null
                    || (item.getCustomer() != null && StringUtils.isEmpty(item.getCustomer().getId()))){
                throw new RuntimeException("单位应收时，客户不能为空！");
            }
            paymentacount = paymentacount + item.getAmount();
        }

        if(Arith.compare(paymentacount, amount, 0.01) != 0){
            throw new RuntimeException("支付金额与订单总金额不相等！");
        }
        return false;
    }

    /**
     * 平台公司
     **/
    @Transient
    private PartyRole platformCompany;


    public PartyRole getPlatformCompany() {
        if (platformCompany != null) return platformCompany;
        String topic = "event:fn.contract.findFirstValidFnContractCompanyByPartnerId";
        String platformCompanyId = (String) EventUtil.sendSynEvent(this, topic, MapUtil.mapper("partnerId", getCompany().getId())).stream().findFirst().get();
        if (!StringUtils.isEmpty(platformCompanyId)) {
            platformCompany = (PartyRole) JpaUtil.getImplementation(SpringManager.getBean(PartyRoleService.class).findOne(platformCompanyId, "Company"));
            platformCompany = MapUtil.getO(MapUtil.mapped(platformCompany), PartyRole.class);
        }
        return  platformCompany;
    }



}
